﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PoshXmpp
{
    public class ReconnectManager
    {
        bool _closingOnPurpose = false;
        public ReconnectManager(XmppClient client)
        {
            client.OnSocketError += new agsXMPP.ErrorHandler(OnClientSocketError);
            client.OnError += new agsXMPP.ErrorHandler(OnClientError);
            client.OnClose += new agsXMPP.ObjectHandler(OnClientClose);
        }

        public void Close()
        {
            _closingOnPurpose = true;
        }

        void OnClientClose(object sender)
        {
            System.Diagnostics.Trace.WriteLine("Client Closing" + (_closingOnPurpose ? " On Purpose " : ""));
            if (!_closingOnPurpose)
            {
                ((XmppClient)sender).Open();
            }
        }

        void OnClientError(object sender, Exception ex)
        {
            System.Diagnostics.Trace.WriteLine(String.Format(
                "Client Error:\n{0}\n{1}\n\n{2}", ex.Message, ex.TargetSite.ToString(), ex.StackTrace));
        }

        void OnClientSocketError(object sender, Exception ex)
        {
            System.Diagnostics.Trace.WriteLine(String.Format(
                "Client Socket Error:\n{0}\n{1}\n\n{2}", ex.Message, ex.TargetSite.ToString(), ex.StackTrace));
        }
    }
}
